<template>
  <div>
    <Form ref="queryForm" :model="dataToQuery" :label-width="120">
      <Row v-if="!switchFlag" class="query-form" >
        <i-col span="8">
          <FormItem label="二级集团：" >
            <two-level-org org-code v-model="dataToQuery.twolevelOrgId" ></two-level-org>
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="企业名称：">
            <company-select v-model="dataToQuery.companyName"></company-select>
          </FormItem>
        </i-col>
        <i-col span="8">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开<Icon type="ios-arrow-down"/></Button>
          <Button @click="resetRe" class="ivu-btn-reset"  >重置</Button>
          <Button type="primary" class="ivu-btn-query"   icon="md-search"  @click="query">查询</Button>
        </i-col>
      </Row>
      <Row v-if="switchFlag" class="query-form">
        <i-col span="8">
          <FormItem label="二级集团：" >
            <two-level-org org-code v-model="dataToQuery.twolevelOrgId" ></two-level-org>
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="企业名称：">
            <company-select v-model="dataToQuery.companyName"></company-select>
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="预算年度：">
            <DatePicker v-model="dataToQuery.inputYear"  type="year" placeholder="请选择投入年份" style="width: 100%" :clearable="false"></DatePicker>
          </FormItem>
        </i-col>
      </Row>
      <Row v-if="switchFlag" class="query-form">
        <i-col span="8">
          <FormItem label="预算科目：">
            <Select class="query-form-el" placeholder="请选择预算科目" type='text' v-model='dataToQuery.codingCodeId'>
              <Option v-for="item in problemTypeList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col span="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起<Icon type="ios-arrow-up" /></Button>
          <Button @click="resetRe" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </i-col>
      </Row>
    </Form>
    <Row class="query-form">
      <i-col span="24">
        <Button size="large" class="ivu-btn-add" icon="md-add"  @click="addInfo">新增</Button>
      </i-col>
    </Row>
    <Table ref='table' :height="tableHeight"  no-data-text="没有查询到相关数据!" :loading='pageStatus.loading' :span-method="handleSpan"
           :border=true :columns="columns1"  :data="dataTable" >
    </Table>
    <Row style="margin-right:10px;">
      <i-col span="24" >
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
      </i-col>
    </Row>
    <Modal  title="年度安全投入预算" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow"  :width=800  class-name='limit-height-dialog'>
      <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':'rpt-form'" :show-message="false" :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?170:null" :label-position="mode === 'view'?'right':'top'">
        <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
          <i-col span="12">
            <FormItem label='单位名称：' prop='orgId'>
              <div v-if="mode === 'view'">{{ dataToView.orgName }}</div>
              <cascaderDom ref="queryOrgCascader" @setOrgInfo="setOrgId" :setCurrentName="{value: dataToView.orgId, label : dataToView.orgName}"
                                     :rootOrgId="currentUser.companyId" class="query-form-el" v-else
                                     :orgTree="true"></cascaderDom>
            </FormItem>
          </i-col>
          <i-col span="12">
          </i-col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
          <i-col span="12">
            <FormItem label='预算年度：' prop='inputYear'>
              <div v-if="mode === 'view'">{{ dataToView.year }}</div>
              <DatePicker v-model="dataToView.inputYear" type="year" placeholder="请选择投入年份" style="width: 100%" :clearable="false" v-else></DatePicker>
            </FormItem>
          </i-col>
          <i-col span="12">
          </i-col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
          <i-col span="12">
            <FormItem label='预算科目：' prop='codingCodeId'>
              <div v-if="mode === 'view'">{{ problemTypeList[dataToView.codingCodeId]['codingName']  }}</div>
              <Select class="query-form-el" placeholder="请选择事件类型" type='text' v-model='dataToView.codingCodeId' v-else style="width:100%">
                <Option v-for="item in problemTypeList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="12">
          </i-col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
          <i-col span="12">
            <FormItem label='预算金额（万元）：' prop='budgetAmount'>
              <div v-if="mode === 'view'">{{ dataToView.budgetAmount }}</div>
              <InputNumber :min="0" v-model="dataToView.budgetAmount"  v-else style="width:100%"></InputNumber>
            </FormItem>
          </i-col>
          <i-col span="12">
          </i-col>
        </Row>
      </Form>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-save' @click="submit('dialogForm')" >确定</Button>
        <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
  import {Api} from '@/api/index.js'
  import {formatDate} from '@/tools/index'
  let cascaderDom = () => import('@/components/cascader-dom.vue');
  import pageCommonFunction from '@/components/pageCommonFunction.js'
  export default {
  name: "safetyProductionBudgetList",
  components: {cascaderDom },
  data() {
    return {
      ...this.createCommonDataField(),
      columns1: [
        { title: '序号', width: 80, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        { key:'orgName',title: '所属单位',  align: 'center', minWidth:150},
        { key:'year',title: '预算年度',  align: 'center' , minWidth:160},
        { key:'codingCodeId',title: '预算科目',  align: 'center', minWidth:150, tooltip: true,
          render: (h, params) => {
            return h('span', params.row.codingCodeId !== null ? this.problemTypeList[params.row.codingCodeId]['codingName']: '')
          }
        },
        { key:'budgetAmount',title: '预算金额（万元）',  align: 'center', render: (h, params)=>{return h('span', params.row.budgetAmount)}, minWidth:160 },
        { key:'totalAmount',title: '总金额（万元）',  align: 'center', width: 200 , tooltip: true},
        this.getActionColumns2(),
      ],
      tableHeight:10,
      ruleCustom: {
        orgId: [ { required: true, message: ' ', trigger: 'change' } ],
        year: [ { required: true, message: ' ', trigger: 'change' } ],
        codingCodeId: [ { required: true, message: ' ', trigger: 'change' } ],
        budgetAmount: [ { required: true, message: ' ', trigger: 'change', type: 'number' } ]
      },
      queryUrl:Api.querySafetyProductionBudget,
      exportUrl:Api.exportProblemFeedback,
      deleteUrl:Api.deleteSafetyProductionBudget,
      getUrl:Api.getProblemFeedback,
      updateUrl:Api.updateSafetyProductionBudget,
      saveUrl:Api.addSafetyProductionBudget,
      problemTypeList: [],
      fileUrl: Api.interestedPartiesUserFile,
      uploadList:[],
    };
  },
  async mounted() {
    await this.$http.get(Api.queryCodeDetailBySortId + '/PRO-00001', {params: {}}).then((res) => {
      this.problemTypeList = this.dictListToMap(res.data.data);
    });
    this.setTableHeight();
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    query() {
      if(this.dataToQuery.inputYear != undefined && this.dataToQuery.inputYear != null && this.dataToQuery.inputYear != ''){
        this.dataToQuery.year = new Date(this.dataToQuery.inputYear).getFullYear();
      }
      this.dataToQuery.orgName = this.currentUser.companyName;
      this.queryData();
    },
    queryData(){
      this.pageStatus.loading = true
      let data = {
          startPage: this.pagedata.currentPage,
          size: this.pagedata.pageSize,
          conditions: this.dataToQuery
      };
      this.$http.post(this.queryUrl, data).then((res) => {
          if (res.data.status === 201) {
              this.$Message.error(res.data.msg);
          }
          this.dataTable = this.integratedData(res.data.data.data);

          this.pagedata.total = res.data.data.totalSize;
          this.pageStatus.loading = false
      }).catch(e => {
          this.$Message.error("数据获取失败")
          this.pageStatus.loading = false
      })
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 44;
      } else {
        this.tableHeight = this.tableHeight - 44;
      }
    },
    submit(name) {
      if(this.mode != 'edit'){
        this.dataToView.problemNo = this.currentUser.loginId;
        this.dataToView.feedbackUser = this.currentUser.userName;
        this.dataToView.createUserId = this.currentUser.userId;
      }else{
        this.dataToView.updateUserId = this.currentUser.userId;
      }
      this.dataToView.year = new Date(this.dataToView.inputYear).getFullYear();
      this.submitAjax(name);
    },
    deleteData(params) {
      this.$set(params.row, 'id', params.row.budgetId);
      this.deleteDateAjax(params);
    },
    getActionColumns2(noRender){
      return {
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 200,
        align: 'center',
        render: (h, params) => {
          if (noRender instanceof Function && noRender(params)) {
            return;
          }
          return h('div', [
            h('A', {
              props: {type: 'primary', size: 'small'},
              style: {fontSize: '14px',},
              on: {
                click: () => {
                  this.viewData(params);
                  this.getFiles1();
                }
              }
            }, '详情'),
            h('Divider', {props: {type: 'vertical'}}, ''),
            h('A', {
                props: {type: 'primary', size: 'small'},
                disabled: true,
                style: {fontSize: '14px'},
                on: {
                    click: () => {
                        this.openEdit(params);
                    }
                }
            }, '修改'),
            h('Divider', {props: {type: 'vertical'}}, ''),
            h('A', {
              props: {type: 'primary', size: 'small'},
              style: {fontSize: '14px', color: 'red'},
              on: {
                click: () => {
                  this.deleteData(params);
                }
              }
            }, '删除')
          ]);
        }
      }
    },
    openEdit(params){
      params.row.inputYear = formatDate(new Date(params.row.year),'yyyy-MM-dd hh:mm:ss');
      params.row.budgetAmount = ~~params.row.budgetAmount;
      this.editData(params);
      this.$refs.queryOrgCascader.setCurrentOrg()
    },
    setOrgId(data){
      this.$set(this.dataToView, 'orgId',  data[data.length - 1]);
    },
    setOrgId2(data){
      this.$set(this.dataToQuery, 'orgId',  data[data.length - 1]);
    },
    handleSpan({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 1) {
        return {
          rowspan: row.mergeCol === 0 ? 0 : row.mergeCol,
          colspan: row.mergeCol === 0 ? 0 : 1
        };
      }
      if (columnIndex === 2 ) {
        return {
            rowspan: row.mergeCol2 === 0 ? 0:row.mergeCol2,
            colspan: row.mergeCol2 === 0 ? 0:1
        };
      }
      if (columnIndex === 5 ) {
        return {
            rowspan: row.mergeCol2 === 0 ? 0:row.mergeCol2,
            colspan: row.mergeCol2 === 0 ? 0:1
        };
      }
    },
    resetRe(){
      setTimeout(() => {
        this.$refs.queryOrgCascader2.resetCurrentOrg();
      }, 100)
      this.reset();
    },
    integratedData(data){
      let that = this;
      // 获取所有的不同年龄值
      let arrId = [];
      let arrId2 = [];

      data.forEach(i => {
        !arrId.includes(i.orgName) ? arrId.push(i.orgName) : arrId;
        !arrId2.includes(i.parentId) ? arrId2.push(i.parentId) : arrId2;
      });
      // 提前为每个年龄值设置跨行数为0
      let arrObj = [];
      let arrObj2 = [];
      arrId.forEach(j => {
        arrObj.push({
          id: j,
          num: 0
        })
      })
      arrId2.forEach(j => {
        arrObj2.push({
          id: j,
          num: 0
        })
      })
      // 计算每个年龄的可跨行数
      data.forEach(k => {
        arrObj.forEach(l => {
          k.orgName === l.id ? l.num++ : l.num;
        })
        arrObj2.forEach(l => {
          k.parentId === l.id ? l.num++ : l.num;
        })
      })
      data.forEach(m => {
        arrObj.forEach((n, index) => {
          if (m.orgName === n.id) {
            if (arrId.includes(m.orgName)) {
              m.mergeCol = n.num;
              arrId.splice(arrId.indexOf(m.orgName), 1);
            } else {
              m.mergeCol = 0;
            }
          }
        })
        
        arrObj2.forEach((n, index) => {
          if (m.parentId === n.id) {
            if (arrId2.includes(m.parentId)) {
              m.mergeCol2 = n.num;
              arrId2.splice(arrId2.indexOf(m.parentId), 1);
            } else {
              m.mergeCol2 = 0;
            }
          }
        })

      })
      return data;
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      return a;
    },
    formatDate2(date, fmt) {
      if (typeof date == 'string') {
        return date;
      }
      if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
      if (!date || date == null) return null;
      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      for (let k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
      return fmt
    },
  }
}

</script>